package com.hele.sts.action;

import com.hele.sts.pub.R;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

@Controller
@RequestMapping("/api")
public class VerifyController {
    /**
     * @param verifyCode 前端用户输入返回的验证码
     * 参数若需要，自行添加
     */
    @RequestMapping(value = "/verify")
    @ResponseBody
    public R checkcode(@RequestParam(value = "verifyCode") String verifyCode, HttpServletRequest request,
                       HttpSession session) throws Exception {
      
        // 获得验证码对象
        Object cko = session.getAttribute("simpleCaptcha"); 
        if (cko == null) {
            request.setAttribute("errorMsg", "请输入验证码！");
            return R.error("01","请输入验证码！");
        }
        String captcha = cko.toString();
        // 判断验证码输入是否正确

        Long codeTime = Long.valueOf(session.getAttribute("codeTime") + "");

        if (StringUtils.isEmpty(verifyCode) || captcha == null || !(verifyCode.equalsIgnoreCase(captcha))) {
            request.setAttribute("errorMsg", "验证码错误！");
            return R.error("02","验证码错误，请重新输入！");

          // 验证码有效时长为1分钟

        } else if ((System.currentTimeMillis()- codeTime) / 1000 / 60 > 1) {
            request.setAttribute("errorMsg", "验证码已失效，请重新输入！");
            return R.error("03","验证码已失效，请重新输入！");
        } else {
            session.setAttribute("captchaVerified","1");
           // 在这里可以处理自己需要的事务，比如验证登陆等

            return R.ok();
        }
    }
}
